<template>
  <div class="product-container" v-ai-tip>
    <div class="chat-list">
      <div v-for="item in dataList" :key="item">
        <chatBubble
          :item="item"
          :key="item"
          @onSelectItem="onSelectItem"
          class="chatBubble"
        />
      </div>

      <followUp
        :suggestions="suggestions"
        :isLoading="isLoadingSuggestions"
        v-show="suggestions.length > 0 || isLoadingSuggestions"
        @onSelectSuggestion="onSelectSuggestion"
      />

      <div class="extra-view" v-show="showExtra">
        <div class="btn" @click="supplementInfo">
          <img src="../../icons/svg//productAssistant/addInfo.svg" />
          <p>继续补充信息</p>
        </div>
        <div class="btn" @click="generateQuotation">
          <img src="../../icons/svg//productAssistant/generateQuotation.svg" />
          <p>生成报价单</p>
        </div>
      </div>
      <!-- 放一空白的占位，否则最后一个元素为隐藏时，滚动底部方法无效 -->
      <div style="height: 30px" />
    </div>

    <div class="stop-answer" @click="stopAnswer" v-show="isLoading">
      <div class="color-view"></div>
      停止回答
    </div>

    <div :class="['bottom-view', isFocus ? '' : 'safe-area-bottom']">
      <div class="meeting-record" @click="clickMeetRecord">
        <img src="../../icons/svg/productAssistant/meet_logo.svg" />
        绚星会议记录
      </div>
      <div :class="['bottom-input-bar', 'pb-8']">
        <img
          src="../../icons/svg/productAssistant/menu_icon.svg"
          @click="showLeftNavigationAction"
        />
        <div :class="`input-box `">
          <div class="selected-record-box" v-if="selectedRecord">
            <van-icon
              name="clear"
              class="clear-icon"
              size="24"
              @click="onClickClearRecord"
            />
            <p>{{ selectedRecord.subject }}</p>
            <p>{{ selectedRecord.salesMateCustomerName }}</p>
          </div>
          <div :class="`flex flex-row justify-around bg-white w-full align-middle`">
            <van-field
              :class="['input-field', meetRecord ? 'mb-2' : '']"
              ref="inputField"
              v-model="inputMsg"
              placeholder="你可以问我任何问题"
              enterkeyhint="send"
              :border="false"
              @keydown.enter="handleSend"
              @focus="onFocus"
              @blur="onBlur"
            />

            <img
              :class="['send-btn', allowSend ? '' : 'disable-bg']"
              src="../../icons/svg/productAssistant/send_icon.svg"
              v-show="isFocus"
              @click="handleSend"
            />
          </div>
        </div>
      </div>
    </div>

    <van-popup
      v-model:show="showLeftNavigation"
      position="left"
      round
      :style="{ height: '100%', width: '80%' }"
    >
      <leftNavigation
        @onClose="
          () => {
            showLeftNavigation = false;
          }
        "
      />
    </van-popup>

    <van-dialog
      v-model:show="showEditDialog"
      title="编辑"
      show-cancel-button
      @confirm="onConfirmRecordName"
    >
      <div class="dialog-content">
        <van-field
          class="text-field"
          v-model="recordName"
          placeholder="请输入新名称"
          :maxlength="20"
        />
      </div>
    </van-dialog>

    <van-popup
      v-model:show="showMeetRecord"
      closeable
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <meetRecord @close="() => (showMeetRecord = false)" />
    </van-popup>
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch, nextTick } from "vue";
import { useProductStore } from "@/store";
import { useRoute } from "vue-router";
import chatBubble from "./components/chatBubble.vue";
import leftNavigation from "./components/leftNavigation.vue";
import { setToken, getToken } from "../../utils/auth";
import { showToast } from "vant";
import meetRecord from "./components/meetRecord.vue";
import followUp from "./components/followUp.vue";

const store = useProductStore();
const route = useRoute();

onMounted(() => {
  initData();
});

const showExtra = computed(() => {
  return store.showExtra;
});

const dataList = computed(() => store.chatList);
const selectedRecord = computed(() => store.selectedRecord);
// const meetRequireMent = computed(() => store.meetRequireMent);

async function initData() {
  const { token, isTest, userId } = route.query;
  if (isTest) {
    setToken(
      "Bearer2 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzaW1wbGVMb2dpbiI6dHJ1ZSwiaXNzIjoib2N0IiwibmFtZSI6IuacseW6huelpSIsImlkIjoiZjBmZTZmYmQtYzdkMS00NTllLWJkMDYtODczZDA1ZGY1OWZjIiwib3JnSWQiOiIyNDJiMjU1YS1hNWE4LTQ4MGMtYTI1MS0zOWNhZTAyMGVhNjAifQ.JIX-xDVThCQwGqKo_U-pRgMPqmIhkglxchCJf5o8B1I"
    );
  }
  if (token && token.length > 0) {
    setToken(token);
  }

  store.userId = userId;
  if (!store.userId) {
    const userInfoStr = localStorage.getItem("yxt-userInfo");
    const userInfo = JSON.parse(userInfoStr);
    if (userInfo) {
      console.log("userInfo: ", userInfo);
      store.userId = userInfo.id;
    }
  }

  const categorys = await store.getGoodsCategoryAction();
  store.addWelcomeMessage();
}

function onSelectItem(item) {
  const { name } = item;
  store.getGoodsPromptAction(item);
}

function generateQuotation() {
  store.generateQuotation("生成报价单");
  scrollBottom();
}

function supplementInfo() {
  store.supplementInfo("继续补充信息");
  scrollBottom();
}

function stopAnswer() {
  store.stopAnswer();
}

// AI 建议问题
const suggestions = computed(() => {
  return store.suggestions;
});

function onSelectSuggestion(content) {
  store.sendCozeGoodPromptAction(content);
  scrollBottom();
}

// 处理发送消息
const inputMsg = ref("");
const inputField = ref(null);
const isFocus = ref(false);

// const disableField = computed(() => {
//   return (
//     store.currentStepType === "chooseCategory" ||
//     isLoading.value ||
//     store.currentStepType === "readStream"
//   );
// });

const allowSend = computed(() => {
  return inputMsg.value.length > 0;
});

function handleSend(e) {
  console.log("handleSend :>> ", e);
  if (store.currentStepType === "chooseCategory") {
    showToast("请先选择商品分类");
    return;
  }
  if (inputMsg.value.length === 0 && !selectedRecord.value) {
    showToast("请先选择会议记录或输入内容");
    return;
  }
  if (isLoading.value) {
    showToast("请求中。。。稍后再试");
    return;
  }
  if (store.currentStepType === "readStream") {
    showToast("请稍后再试");
    return;
  }

  let msg = "";
  if (selectedRecord.value) {
    const { subject, salesMateCustomerName, conferenceId } = selectedRecord.value;
    let msgHead = `${subject} | ${salesMateCustomerName} | ${conferenceId}`;
    msg = `${msgHead} \n ${store.meetRequireMent} \n${inputMsg.value}`;
    store.clearSelectedRecord();
  } else {
    msg = inputMsg.value;
  }
  store.sendCozeGoodPromptAction(msg);
  inputMsg.value = "";
  inputField.value.blur();
  scrollBottom();
}

function onFocus() {
  isFocus.value = true;
}
function onBlur() {
  setTimeout(() => {
    isFocus.value = false;
  }, 200);
}

// 处理抽屉
const showLeftNavigation = ref(false);
function showLeftNavigationAction(params) {
  // if (store.currentStepType === "readStream") {
  //   showToast("等待结果中，请稍后再试");
  //   return;
  // }
  showLeftNavigation.value = true;
}

// 编辑名称 （因为dialog在抽屉页面显示不全,移动到主页面展示）
const showEditDialog = computed({
  get() {
    return store.showEditDialog;
  },
  set(newValue) {
    store.changeEditDialogState(newValue);
  },
});

const recordName = computed({
  get() {
    return store.dialogFieldValue;
  },
  set(newValue) {
    store.changeDialogFieldValue(newValue);
  },
});

function onConfirmRecordName() {
  const name = store.dialogFieldValue;
  store.changeDialogFieldValue("");
  store.changeGoodsChatName(name);
}

function scrollBottom() {
  setTimeout(() => {
    let element = document.getElementsByClassName("chat-list")[0];
    let lastChild = element.lastElementChild;
    lastChild.scrollIntoView({
      behavior: "smooth",
      block: "end",
      inline: "nearest",
    });
  }, 200);
}

// 处理loading状态
const isLoading = computed(() => {
  return store.isLoading;
});

const isLoadingSuggestions = computed(() => {
  return store.isLoadingSuggestions;
});

// 流式回答内容
const tempAnswer = computed(() => store.tempAnswer);

watch(isLoading, (newValue, oldValue) => {
  if (newValue === false && oldValue === true) {
    scrollBottom();
  }
});
watch(tempAnswer, () => scrollBottom());
watch(suggestions, () => scrollBottom());

const showMeetRecord = ref(false);

function clickMeetRecord() {
  if (store.currentStepType === "chooseCategory") {
    showToast("请先选择商品分类");
    return;
  }
  showMeetRecord.value = true;
}

function onClickClearRecord() {
  // this.selectedRecord = null;
  store.clearSelectedRecord();
}
</script>

<style lang="less" scoped>
.product-container {
  // checkbox 半选中状态颜色
  --van-checkbox-checked-icon-color: #436bff;

  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  overflow: hidden;
  background: linear-gradient(
    to bottom right,
    #c1ceff,
    #e8ecff,
    #eff3fd,
    #e6edfa,
    #d6e9ff,
    #eff3fd
  );
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.safe-area-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.chat-list {
  flex: 1;
  overflow-y: auto;
}

.bottom-view {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: space-between;
  box-sizing: border-box;
  width: 100%;
  padding: 0 16px;

  .bottom-input-bar {
    width: 100%;
    display: flex;
    flex-direction: row;
    margin-top: 12px;

    img {
      width: 32px;
      height: 32px;
      margin-top: 6px;
    }

    .input-field {
      padding: 0;
      height: 26px;
      line-height: 26px;
      margin-top: 7px;
      background-color: transparent;
    }

    .input-field :focus {
      height: 26px;
      line-height: 26px;
    }

    .send-btn {
      width: 42px;
      height: 36px;
      margin-left: 8px;
    }

    .disable-bg {
      opacity: 0.8;
    }
  }

  .meeting-record {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 140px;
    height: 30px;
    border-radius: 15px;
    margin-left: 42px;
    font-size: 12px;
    background-color: white;

    img {
      margin-right: 8px;
    }
  }
}

.input-box {
  display: flex;
  flex-direction: column;
  min-height: 44px;
  border-radius: 22px;
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: start;
  padding: 0 10px 0px 22px;
  flex: 1;
  margin-left: 12px;

  .selected-record-box {
    margin-top: 6px;
    background-color: rgba(241, 242, 250, 0.5);
    padding: 10px;
    border-radius: 12px;
    position: relative;

    .clear-icon {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
}

.extra-view {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
  padding: 0 10px;

  .btn {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 32px;
    border-radius: 16px;
    background-color: white;
    font-size: 12px;
    color: #595959;
    padding: 0 12px;
    margin-left: 12px;

    img {
      margin-right: 4px;
    }
  }
}

.dialog-content {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  margin: 24px 0;

  .text-field {
    width: 80%;
    border-radius: 4px;
    border: 1px solid #436bff;
  }
}

.stop-answer {
  width: 140px;
  height: 30px;
  border-radius: 15px;
  margin: 0 auto;
  font-size: 12px;
  background-color: white;
  display: flex;
  flex-direction: row;
  align-items: center;
  position: relative;
  bottom: 30px;
  justify-content: center;

  .color-view {
    width: 8px;
    height: 8px;
    border-radius: 2px;
    margin-right: 4px;
    background-color: #436bff;
  }
}
</style>
